export class Node {
  val: number;
  children: Node[];
  constructor(val?: number) {
    this.val = val === undefined ? 0 : val;
    this.children = [];
  }
}

// 数组转n叉树
export const arr2nTree = (arr: (number | null)[] | null, n: number): Node | null => {
  if (!arr || !arr.length) return null;
  const root = new Node(arr.shift());
  const nodeArr: Node[] = [root];
  while (arr.length) {
    const node = nodeArr.shift();
    for (let index = 0; index < n; index++) {
      if (!arr.length) break; // 检查是否还有剩余元素
      const val = arr.shift();
      if (val === null) continue;
      const temp = new Node(val);
      node.children.push(temp);
      nodeArr.push(temp);
    }
  }

  return root;
};

// n叉树转数组
